//
//  M1BlackListVC.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/19.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1BlackListVC.h"
#import "M1RecentFriendCell.h"

#import "MJRefresh.h"
#import "UITableView+Placeholder.h"

@interface M1BlackListVC ()

@property (nonatomic, strong) NSMutableArray *m1_dataArr;

@property (nonatomic, strong) UIView *m1_editingView;

@property (nonatomic, strong) UIBarButtonItem *m1_barBtm;

@property (nonatomic, assign) NSInteger m1_page;

@end

@implementation M1BlackListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"小黑屋";
    
    self.m1_dataArr = [NSMutableArray arrayWithCapacity:0];
    
    self.m1_barBtm = [[UIBarButtonItem alloc] initWithTitle:@"解除" style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)];
    _m1_barBtm.tintColor = m1_color(0x333333);
    self.navigationItem.rightBarButtonItem = _m1_barBtm;
    
    [self createUI];
}

- (void)rightAction:(UIBarButtonItem *)item{
    if ([item.title isEqualToString:@"解除"]) {
        if (self.m1_dataArr.count == 0) {
            return;
        }
        item.title = @"取消";
        [self.m1_tableView setEditing:YES animated:YES];
        [self showEitingView:YES];
    }else{
        item.title = @"解除";
        [self.m1_tableView setEditing:NO animated:YES];
        
        [self showEitingView:NO];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.isEditing) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.m1_dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    M1RecentFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:m1_tableViewCellIdentifier];

    cell.m1_user = self.m1_dataArr[indexPath.row];
    
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)showEitingView:(BOOL)isShow{
    CGFloat showHeight = iPhoneX?-45 - 34:-45;
    CGFloat noHeight = iPhoneX?45 + 34:45;
    [self.m1_editingView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(isShow?showHeight:noHeight);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)m1_buttonClick:(UIButton *)sender{
    if ([[sender titleForState:UIControlStateNormal] isEqualToString:@"解除"]) {
        /** 数据清空情况下取消编辑状态*/
        if (self.m1_dataArr.count == 0) {
            self.navigationItem.rightBarButtonItem.title = @"解除";
            [self.m1_tableView setEditing:NO animated:YES];
            [self showEitingView:NO];
            /** 带MJ刷新控件重置状态
             [self.tableView.footer resetNoMoreData];
             [self.tableView reloadData];
             */
        }else{
            __weak typeof(self)weakSelf = self;
            
            NSMutableIndexSet *insets = [[NSMutableIndexSet alloc] init];
            NSMutableArray *idArr = [NSMutableArray arrayWithCapacity:0];
            NSMutableArray *uidArr = [NSMutableArray arrayWithCapacity:0];
            [[self.m1_tableView indexPathsForSelectedRows] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [insets addIndex:obj.row];
//                [idArr addObject:weakSelf.m1_dataArr[obj.row][@"id"]];
                M1User *userM = weakSelf.m1_dataArr[obj.row];
                [uidArr addObject:userM.basic.to_uid];
            }];
            
            if (uidArr.count == 0) {
                [M1Alert m1_alertWithTitle:nil message:@"请选择您要解除的用户"];
            }else{
                NSDictionary *dic = @{@"to_uid":[uidArr componentsJoinedByString:@","]};
                [M1HttpNet requestWithMethod:m1_undo_blacklist_url params:dic success:^(id resDic, NSInteger code, NSString *message) {
//                    for (NSString *uid in uidArr) {
//                        EMError *error = [[EMClient sharedClient].contactManager removeUserFromBlackList:[[NSString stringWithFormat:@"%@", uid] MD5]];
//                        if (!error) {
//                            NSLog(@"发送成功");
//                        }
//                    }
                    [M1Alert m1_alertWithTitle:@"提示" message:@"解除成功" buttonTitles:@[@"确定"] action:^(NSInteger index) {
                        [weakSelf.m1_dataArr removeObjectsAtIndexes:insets];
                        [weakSelf.m1_tableView deleteRowsAtIndexPaths:[weakSelf.m1_tableView indexPathsForSelectedRows] withRowAnimation:UITableViewRowAnimationFade];
                        if ([weakSelf.m1_dataArr count] == 0) {
//                            weakSelf.vacancy.hidden = NO;
//                            [weakSelf popViewController];
                            [weakSelf m1_back];
                        }
                    }];
                } fail:^(id resDic, NSInteger code, NSString *message) {
                    [M1Alert m1_alertWithTitle:nil message:message];
                } showAni:YES];
            }
        }
        
    }else if ([[sender titleForState:UIControlStateNormal] isEqualToString:@"全选"]) {
        [self.m1_dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.m1_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
        }];
        
        [sender setTitle:@"全不选" forState:UIControlStateNormal];
    }else if ([[sender titleForState:UIControlStateNormal] isEqualToString:@"全不选"]){
        [self.m1_tableView reloadData];
        /** 遍历反选
         [[self.tableView indexPathsForSelectedRows] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
         [self.tableView deselectRowAtIndexPath:obj animated:NO];
         }];
         */
        
        [sender setTitle:@"全选" forState:UIControlStateNormal];
        
    }
}

- (void)createUI{
    [self.m1_tableView registerClass:[M1RecentFriendCell class] forCellReuseIdentifier:m1_tableViewCellIdentifier];
    
    [self.view addSubview:self.m1_editingView];
    [self.m1_editingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.equalTo(@45);
        make.bottom.equalTo(self.view).offset(iPhoneX?45+ 34:45);
    }];
    
    __weak typeof(self)weakSelf = self;
    self.m1_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.m1_page = 1;
        [weakSelf.m1_tableView.mj_header beginRefreshing];
        [weakSelf m1_requestList];
    }];
    self.m1_tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.m1_page++;
        [weakSelf.m1_tableView.mj_footer beginRefreshing];
        [weakSelf m1_requestList];
    }];
    [self.m1_tableView.mj_header beginRefreshing];
}

- (void)m1_requestList
{
    NSDictionary *dic = @{@"page":@(_m1_page)};
    [M1HttpNet requestWithMethod:m1_blacklist_url params:dic success:^(id resDic, NSInteger code, NSString *message) {
        NSArray *array = (NSArray *)resDic;
        NSArray *m1_array = [M1User mj_objectArrayWithKeyValuesArray:array];

        if (self.m1_page == 1) {
            self.m1_dataArr = [NSMutableArray arrayWithArray:m1_array];
        } else {
            [self.m1_dataArr addObjectsFromArray:m1_array];
        }
        
        self.m1_tableView.imgName = @"data_none";
        self.m1_tableView.noneTitle = @"空空如也";
        self.m1_tableView.m1_needPlace = @(1);
        
        [self.m1_tableView reloadData];
        [self.m1_tableView.mj_header endRefreshing];
        [self.m1_tableView.mj_footer endRefreshing];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:message];
        [self.m1_tableView.mj_header endRefreshing];
        [self.m1_tableView.mj_footer endRefreshing];
    } showAni:NO];
}

- (UIView *)m1_editingView{
    if (!_m1_editingView) {
        _m1_editingView = [[UIView alloc] init];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor redColor];
        [button setTitle:@"解除" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(m1_buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_m1_editingView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.bottom.equalTo(self.m1_editingView);
            make.width.equalTo(self.m1_editingView).multipliedBy(0.5);
        }];
        
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor darkGrayColor];
        [button setTitle:@"全选" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(m1_buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_m1_editingView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.equalTo(self.m1_editingView);
            make.width.equalTo(self.m1_editingView).multipliedBy(0.5);
        }];
    }
    return _m1_editingView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
